Component({
  behaviors: [require('../common/share-behavior').default],
  innerInterval: 0,
  videoId: -1,
  properties: {
    colData: {
      type: Array,
      value: []
    },
  },
  data: {
    col: [],
    loaded: false,
    arReady: false,
    resourceLoaded: false,
    loadedAssets: {},
    resources: {},
    marker: {},
    videoIdList: [],
    videoLoaded: false,
    videoRatioLoaded: false,
    markerWidth: 0,
    markerHeight: 0,
    isTracking: false,
    isTracked: false,
    curMarker: {},
    curMarkerRes: {}
  },
  observers: {
    colData(newVal) {
      console.log('observers colData');
      if (newVal.length > 0) {
        this._parseColdata(newVal);
      }
    },
  },
  lifetimes: {
    attached() {
      console.log('attached', this.data.colData);
    }
  },
  methods: {
    _parseColdata(colData) {
      console.log('_parseColdata');
      let gltfResources = [];
      let videoResources = [];
      let imgResources = [];
      let marGltf = [];
      let marVideo = [];
      let marImg = [];
      colData.forEach(ele => {
        if (ele.resources.length > 0) {
          let marRes = [];
          switch (ele.type) {
            case 'gltf':
              ele.resources.forEach(res => {
                gltfResources.push({
                  id: res.id,
                  url: res.src
                });
                marRes.push(this._getMarResItem(ele.type, res));
              });
              marGltf.push({
                id: ele.id,
                markerImg: ele.markerImg,
                markerResources: marRes
              });
              break;
            case 'video':
              ele.resources.forEach(res => {
                videoResources.push({
                  id: res.id,
                  assetId: 'video-' + res.id,
                  matId: 'mat-video-' + res.id,
                  url: res.src
                });
                marRes.push(this._getMarResItem(ele.type, res));
              });
              marVideo.push({
                id: ele.id,
                markerImg: ele.markerImg,
                markerResources: marRes
              });
              break;
            case 'img':
              ele.resources.forEach(res => {
                imgResources.push({
                  id: res.id,
                  url: res.src
                });
                marRes.push(this._getMarResItem(ele.type, res));
              });
              marImg.push({
                id: ele.id,
                markerImg: ele.markerImg,
                markerResources: marRes
              });
              break;
          }
        } else {
          console.log('col item：' + ele.id + ' has no resource');
        }
      });
      this.setData({
        col: colData,
        resources: { "gltfResources": gltfResources, "videoResources": videoResources, "imgResources": imgResources },
        marker: { 'gltfs': marGltf, 'videos': marVideo, 'imgs': marImg }
      });
      console.log('data', this.data);
    },
    _getMarResItem(type, data) {
      let pos = this._getXYZString(data.position);
      let ros = this._getXYZString(data.rotation);
      let scale = this._getScaleString(data.scale);
      let newData = {};
      if (type == 'video') {
        newData = { id: data.id, assetId: `${type}-${data.id}`, matId: `mat-video-${data.id}`, src: data.src, position: pos, rotation: ros, scale: scale, width: data.width, height: data.height };
      } else {
        newData = { id: `${type}-${data.id}`, src: data.src, position: pos, rotation: ros, scale: scale };
      }
      return newData;
    },
    _getScaleString(scale) {
      if (typeof scale === 'string' && scale.includes(',')) {
        // 如果是字符串且包含逗号，处理字符串
        return scale.split(',').map(value => parseFloat(value.trim()).toFixed(1)).join(' ');
      } else {
        // 如果是数字或不包含逗号的字符串，使用相同的值
        return `${scale} ${scale} ${scale}`;
      }
    },
    _getXYZString(xyzObj) {
      // 从对象中提取x, y, z的值，并去掉可能的空格
      const x = xyzObj.x.toString().trim();
      const y = xyzObj.y.toString().trim();
      const z = xyzObj.z.toString().trim();

      // 返回格式化后的字符串
      return `${x} ${y} ${z}`;
    },
    handleReady({ detail }) {
      console.log('xr-handleReady');
      const xrScene = this.scene = detail.value;

      console.log('xr-scene', xrScene);
      // 加载场景资源

      if (this.data.resources.gltfResources.length > 0) {
        console.log('load gltfs list:', this.data.resources.gltfResources);
        // try {
        //   this.loadGLTF(this.data.resources.gltfResources)
        // } catch (err) {
        //   console.log('[gltf load] error: ', err)
        // }
      }

      if (this.data.marker.videos.length > 0) {
        const mVideo = this.data.marker.videos;
        console.log('videos list:', mVideo);
        mVideo.forEach(ele => {
          console.log('videos tracker id:', ele.id);
          console.log('videos tracker markerResources:', ele.markerResources);
          // this._loadVideos(ele.markerResources);
        });
      }
      if (this.data.marker.imgs.length > 0) {
        const mImg = this.data.marker.imgs;
        console.log('imgs list:', mImg);
      }

    },
    handleAssetsProgress: function ({ detail }) {
      console.log('assets progress', detail.value);
    },
    handleAssetsLoaded: function ({ detail }) {
      console.log('assets loaded');
      const assets = detail.value.assets;
      console.log('assets', assets);
      this.setData({
        loaded: true,
        loadedAssets: assets
      });
    },

    handleGLTFLoaded({ detail }) {
      const el = detail.value.target;
      const gltf = el.getComponent("gltf");
      const animator = el.getComponent("animator");
      console.log("gltf:", gltf);
      console.log("animator:", animator);
    },
    handleTouchCube: function ({ detail }) {

      const target = detail.value.target;

      console.log(target.material);
      console.log(target.uniforms);
      console.log(target.getData('uniforms'));

      // console.log(target.model);
      // const xrSystem = wx.getXrFrameSystem();
      // const video = this.scene.assets.getAsset('video-texture', 'cat');

      // console.log(video.state);
      // if (!video) {
      //   return;
      // }
      // if (video.state === xrSystem.EVideoState.Idle) {
      //   video.play();
      // } else if (video.state === xrSystem.EVideoState.Playing) {
      //   video.pause();
      // } else if (video.state === xrSystem.EVideoState.Paused) {
      //   video.resume();
      // }
    },
    async _loadGLTF(gltfList) {
      const scene = this.scene
      console.log('before assets', scene.assets);

      const gltfModels = await Promise.all(gltfList.map(gltfItem => scene.assets.loadAsset({
        type: 'gltf',
        assetId: 'gltf-' + gltfItem.id,
        src: gltfItem.url,
      })))
      console.log('glTF asset loaded', gltfModels);
      this.setData({ gltfLoaded: true })
    },
    async _loadVideos(videoList) {
      const scene = this.scene
      console.log('_loadVideos', videoList);
      if (videoList.length > 0) {
        const videoIdList = [];
        const videos = await Promise.all(videoList.map((videoItem) => {
          videoIdList.push(videoItem.id);
          return scene.assets.loadAsset({
            type: 'video-texture',
            assetId: videoItem.id,
            src: videoItem.src,
            options: { autoPlay: true, loop: true, abortAudio: false },
          });
        }));
        videos.map((videoTexture, index) => {
          console.log('videoTexture', videoTexture);
          console.log('texture ', videoTexture.value.texture);
          const videoMat = scene.createMaterial(
            scene.assets.getAsset('effect', 'simple'),
            { u_baseColorMap: videoTexture.value.texture }
          )
          scene.assets.addAsset('material', `mat-video-${videoList[index].id}`, videoMat)
        })
        console.log('video asset loaded')
        this.setData({
          videoIdList: videoIdList,
          videoLoaded: true
        })
      } else {
        this.setData({
          videoIdList: [],
          videoLoaded: false
        });
      }
    },
    async _loadVideoSingle(videoItem) {
      console.log('_loadVideoSingle', videoItem);
      const scene = this.scene;
      let videoOb = scene.assets.getAsset('video-texture', videoItem.id);
      if (videoOb === undefined) {
        const videoTexture = await scene.assets.loadAsset({
          type: 'video-texture',
          assetId: videoItem.id,
          src: videoItem.src,
          options: { autoPlay: true, loop: true, abortAudio: false },
        });
        console.log('videoTexture', videoTexture);
        const videoMat = scene.createMaterial(
          scene.assets.getAsset('effect', 'simple'),
          { u_baseColorMap: videoTexture.value.texture }
        );
        console.log('videoMat', videoMat);
        scene.assets.addAsset('material', `mat-video-${videoItem.id}`, videoMat)
        console.log(`video ${videoItem.id} loaded`)
      } else {
        console.log(`video ${videoItem.id} has loaded`)
      }
    },
    sceneReady: function ({ detail }) {
      console.log('arReady', detail);
      this.setData({
        arReady: true
      })
    },
    releaseVideo(id) {
      console.log('releaseVideo', id);
      if (id !== -1 || id !== undefined) {
        // 存在纹理才进行释放
        const scene = this.scene
        // 释放加载过的资源
        scene.assets.releaseAsset('video-texture', id);
        scene.assets.releaseAsset('material', `mat-video-${id}`);
      }
    },
    changeScene({ detail }) {
      console.log('changeScene', detail);
      const active = detail.value;
      const element = detail.el;
      console.log('tracked element', element);
      const tradkerId = element.id;
      console.log('tracked 当前marker id', tradkerId);
      const trackerList = this.data.col;
      console.log('tracked trackerList', trackerList);
      let curType = '';
      let curResources = [];
      trackerList.forEach(item => {
        console.log('col item', item.id);
        if (('marker-' + item.id) === tradkerId) {
          curType = item.type;
          console.log('当前marker type', curType);
          curResources = item.resources;
          console.log('当前marker resources', curResources);
        }
      });
      this.setData({
        isTracking: !active,
        isTracked: active,
        curMarker: tradkerId,
        curMarkerRes: curResources
      });

      console.log(' 当前marker tracked 状态', active);
      if (active) {
        if ((this.videoId !== undefined) && (this.videoId !== -1) && (this.videoId !== curResources[0].id)) {
          console.log('切换加载视频，旧的需要释放');
          // 处理视频纹理
          // this.releaseVideo(this.videoId);
          // this.videoId = -1;
        }
        this._loadVideoSingle(curResources[0]);
        this.videoId = curResources[0].id;
        this.videoAction(this.videoId, 'play');
        this.triggerEvent('tracked', {
          value: detail
        });
      } else {
        console.log('videoId', this.videoId);
        this.triggerEvent('lostTrack', {
          value: detail
        });
      }
    },
    videoAction(videoId, eve, val = null) {
      console.log('videoAction', videoId, eve);
      const video = this.scene.assets.getAsset('video-texture', videoId);
      console.log('video', video);
      switch (eve) {
        case 'pause':
          video.pause();
          break;
        case 'play':
          video.play();
          break;
        case 'release':
          video.release();
          break;
        case 'consume':
          video.resume();
          break;
        case 'seek':
          video.seek(val);
          break;
        case 'stop':
          video.stop();
          break;
        default:
          console.log(`videoAction ${eve} is not supported`);
          break;
      }
    },
    videoHanler(markerRes, isPlay) {
      console.log('videoHanler', markerRes);
      // this.setData({
      //   videoLoaded: false,
      //   videoRatioLoaded: false,
      // })

      // // 获取识别图，图片比例
      // wx.getImageInfo({
      //   src: markerInfo.markerImg,
      //   success: res => {
      //     const {
      //       width,
      //       height
      //     } = res
      //     const widthDivideHeight = width / height;

      //     if (widthDivideHeight > 1) {
      //       this.setData({
      //         markerWidth: widthDivideHeight * 0.7,
      //         markerHeight: 1 * 0.7,
      //         videoRatioLoaded: true,
      //       });
      //     } else {
      //       this.setData({
      //         markerWidth: 1,
      //         markerHeight: (1 / widthDivideHeight).toFixed(2),
      //         videoRatioLoaded: true,
      //       });
      //     }

      //   },
      //   fail: res => {
      //     console.error(res)
      //   }
      // })

      // try {
      //   this._loadVideoSingle(markerInfo.markerResources[0])
      // } catch (err) {
      //   console.log('[video load] error: ', err)
      // }
      const vId = markerRes[0].id;
      this.videoId = vId;
      console.log(this.data.loadedAssets);
      const video = this.scene.assets.getAsset('video-texture', vId);
      console.log(video);

      if (isPlay) {
        video.play();
      } else {
        video.stop();
      }
    },
    tracked({ detail }) {
      console.log('tracked', detail);
      console.log('scene', this.scene);
    },
    error({ detail }) {
      console.log('error', detail);
    }
  },
  attached: function () {
    console.log('outer attached');
  }, // 此处attached的声明会被lifetimes字段中的声明覆盖
  ready: function () {
    console.log('outer ready');
  },
})